<?php
declare (strict_types = 1);
namespace app\api\logic;
use app\admin\model\Order;
use app\common\model\Cart as cartModel;
use think\facade\Cache; // 使用 Cache facade
use app\admin\model\mk\SeckillPro;
class CrontabLogic
{
	//定时检测秒杀订单是否过期
	function seckillExpiredOrders(){
					// 获取所有过期的订单
		    $redis = Cache::store('redis')->handler();
		    $orders = $redis->keys("order:*");
		    $n = 0;
		    foreach ($orders as $orderKey) {

		    		$order_redis_data =  $redis->get($orderKey);
		    		$arr = json_decode($order_redis_data,true); 
		    		$time_diff = time() - $arr['time'];
		    		if($time_diff > 60){

		    				// 订单过期，恢复库存
				            $orderId = substr($orderKey, 6); // 去除前缀 "order:"

				            $order = cartModel::alias("c")->join("order o","c.guan_oid=o.oid")->field("c.pro_id,o.is_pay,o.oid,o.user_id,o.mk_id")->where("c.guan_oid",$orderId)->find();
				            if($order['is_pay'] === 0){
				            		// 恢复库存
						            $stockKey = "seckill:stock:{$order['mk_id']}";
						            Cache::store('redis')->incrBy($stockKey, 1);

						            // 删除过期订单
						            Cache::store('redis')->del($orderKey);

						            // 清除用户参与标记

						            $userParticipationKey = "seckill:user:{$order['user_id']}:{$arr['uni_id']}:participation";
						            Cache::store('redis')->del($userParticipationKey);
						            $n++;

						            Order::where('oid',$order['oid'])->update(['order_status'=>20,'del_time'=>time()+7*24*3600]);  //7天后数据正式删除
				            }
		    		}

		           	
		            
		         
		    }
		    return $n;
	}
}